<template>
  <div class="dashboard">
    <!-- 欢迎区域 -->
    <div class="welcome-section">
      <div class="welcome-content">
        <div class="user-info">
          <el-avatar :size="80" :src="userInfo.avatar || 'https://via.placeholder.com/80x80/409EFF/ffffff?text=用户'" />
          <div class="user-details">
            <h2>欢迎回来，{{ userInfo.nickName || userInfo.userName }}！</h2>
            <p>{{ getCurrentTime() }}</p>
          </div>
        </div>
        <div class="quick-stats">
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><Calendar /></el-icon>
            </div>
            <div class="stat-content">
              <h3>{{ userStats.totalDays }}</h3>
              <p>学习天数</p>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><Trophy /></el-icon>
            </div>
            <div class="stat-content">
              <h3>{{ userStats.completedExams }}</h3>
              <p>完成考试</p>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon">
              <el-icon><Star /></el-icon>
            </div>
            <div class="stat-content">
              <h3>{{ userStats.achievementPoints }}</h3>
              <p>成就点数</p>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="dashboard-content">
      <div class="content-grid">
        <!-- 学习进度 -->
        <div class="content-card">
          <div class="card-header">
            <h3>学习进度</h3>
            <el-button type="text" @click="viewAllProgress">查看全部</el-button>
          </div>
          <div class="progress-list">
            <div v-for="course in learningProgress" :key="course.id" class="progress-item">
              <div class="course-info">
                <h4>{{ course.name }}</h4>
                <p>{{ course.description }}</p>
              </div>
              <div class="progress-bar">
                <el-progress 
                  :percentage="course.progress" 
                  :color="getProgressColor(course.progress)"
                  :stroke-width="8"
                />
                <span class="progress-text">{{ course.progress }}%</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 最近考试 -->
        <div class="content-card">
          <div class="card-header">
            <h3>最近考试</h3>
            <el-button type="text" @click="viewAllExams">查看全部</el-button>
          </div>
          <div class="exam-list">
            <div v-for="exam in recentExams" :key="exam.id" class="exam-item">
              <div class="exam-info">
                <h4>{{ exam.name }}</h4>
                <p>{{ exam.date }}</p>
              </div>
              <div class="exam-status">
                <el-tag :type="getExamStatusType(exam.status)">
                  {{ exam.status }}
                </el-tag>
              </div>
            </div>
          </div>
        </div>

        <!-- 消息通知 -->
        <div class="content-card">
          <div class="card-header">
            <h3>消息通知</h3>
            <el-button type="text" @click="viewAllMessages">查看全部</el-button>
          </div>
          <div class="message-list">
            <div v-for="message in recentMessages" :key="message.id" class="message-item">
              <div class="message-icon">
                <el-icon :color="getMessageIconColor(message.type)">
                  <component :is="getMessageIcon(message.type)" />
                </el-icon>
              </div>
              <div class="message-content">
                <h4>{{ message.title }}</h4>
                <p>{{ message.content }}</p>
                <span class="message-time">{{ message.time }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 快速操作 -->
        <div class="content-card">
          <div class="card-header">
            <h3>快速操作</h3>
          </div>
          <div class="quick-actions">
            <el-button type="primary" @click="startLearning">
              <el-icon><VideoPlay /></el-icon>
              开始学习
            </el-button>
            <el-button type="success" @click="bookExam">
              <el-icon><Calendar /></el-icon>
              报名考试
            </el-button>
            <el-button type="warning" @click="downloadMaterials">
              <el-icon><Download /></el-icon>
              下载资料
            </el-button>
            <el-button type="info" @click="viewProfile">
              <el-icon><User /></el-icon>
              个人资料
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { 
  Calendar, 
  Trophy, 
  Star, 
  VideoPlay, 
  Download, 
  User,
  Bell,
  Warning,
  Success,
  Info
} from '@element-plus/icons-vue'

const router = useRouter()
const userStore = useUserStore()

// 用户信息
const userInfo = ref(userStore.user || {})

// 用户统计数据
const userStats = ref({
  totalDays: 0,
  completedExams: 0,
  achievementPoints: 0
})

// 学习进度
const learningProgress = ref([])

// 最近考试
const recentExams = ref([])

// 最近消息
const recentMessages = ref([])

// 加载状态
const loading = ref(false)

// 获取用户统计数据
const fetchUserStats = async () => {
  try {
    const response = await getUserStats()
    if (response.code === 200) {
      userStats.value = response.data || {}
    } else {
      console.error('获取用户统计数据失败:', response.msg)
    }
  } catch (error) {
    console.error('获取用户统计数据失败:', error)
  }
}

// 获取学习进度
const fetchLearningProgress = async () => {
  try {
    const response = await getLearningProgress()
    if (response.code === 200) {
      learningProgress.value = response.data || []
    } else {
      console.error('获取学习进度失败:', response.msg)
    }
  } catch (error) {
    console.error('获取学习进度失败:', error)
  }
}

// 获取最近考试
const fetchRecentExams = async () => {
  try {
    const response = await getRecentExams()
    if (response.code === 200) {
      recentExams.value = response.data || []
    } else {
      console.error('获取最近考试失败:', response.msg)
    }
  } catch (error) {
    console.error('获取最近考试失败:', error)
  }
}

// 获取最近消息
const fetchRecentMessages = async () => {
  try {
    const response = await getRecentMessages()
    if (response.code === 200) {
      recentMessages.value = response.data || []
    } else {
      console.error('获取最近消息失败:', response.msg)
    }
  } catch (error) {
    console.error('获取最近消息失败:', error)
  }
}

// 获取当前时间
const getCurrentTime = () => {
  const now = new Date()
  const options = { 
    year: 'numeric', 
    month: 'long', 
    day: 'numeric', 
    weekday: 'long' 
  }
  return now.toLocaleDateString('zh-CN', options)
}

// 获取进度条颜色
const getProgressColor = (progress) => {
  if (progress >= 80) return '#67C23A'
  if (progress >= 60) return '#E6A23C'
  return '#F56C6C'
}

// 获取考试状态类型
const getExamStatusType = (status) => {
  switch (status) {
    case '已完成': return 'success'
    case '已报名': return 'warning'
    case '待报名': return 'info'
    default: return 'info'
  }
}

// 获取消息图标
const getMessageIcon = (type) => {
  switch (type) {
    case 'success': return Success
    case 'warning': return Warning
    case 'info': return Info
    default: return Bell
  }
}

// 获取消息图标颜色
const getMessageIconColor = (type) => {
  switch (type) {
    case 'success': return '#67C23A'
    case 'warning': return '#E6A23C'
    case 'info': return '#409EFF'
    default: return '#909399'
  }
}

// 页面跳转方法
const viewAllProgress = () => {
  router.push('/learning-progress')
}

const viewAllExams = () => {
  router.push('/exams')
}

const viewAllMessages = () => {
//  router.push('/messages')
}

const startLearning = () => {
  router.push('/videos')
}

const bookExam = () => {
  router.push('/exam-booking')
}

const downloadMaterials = () => {
  router.push('/materials')
}

const viewProfile = () => {
  router.push('/profile')
}

onMounted(async () => {
  loading.value = true
  try {
    // 并行加载所有数据
    await Promise.all([
      fetchUserStats(),
      fetchLearningProgress(),
      fetchRecentExams(),
      fetchRecentMessages()
    ])
  } catch (error) {
    console.error('加载仪表板数据失败:', error)
  } finally {
    loading.value = false
  }
})
</script>

<style scoped>
.dashboard {
  min-height: 100vh;
  background: #f5f7fa;
}

.welcome-section {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 40px 0;
  margin-bottom: 30px;
}

.welcome-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 30px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.user-details h2 {
  margin: 0 0 5px 0;
  font-size: 1.8rem;
}

.user-details p {
  margin: 0;
  opacity: 0.9;
}

.quick-stats {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
}

.stat-card {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 12px;
  padding: 20px;
  display: flex;
  align-items: center;
  gap: 15px;
  min-width: 150px;
}

.stat-icon {
  font-size: 2rem;
  opacity: 0.8;
}

.stat-content h3 {
  margin: 0 0 5px 0;
  font-size: 1.5rem;
}

.stat-content p {
  margin: 0;
  opacity: 0.8;
  font-size: 0.9rem;
}

.dashboard-content {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.content-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 30px;
}

.content-card {
  background: white;
  border-radius: 12px;
  padding: 25px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.card-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 1.3rem;
}

.progress-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.progress-item {
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 15px;
}

.progress-item:last-child {
  border-bottom: none;
  padding-bottom: 0;
}

.course-info h4 {
  margin: 0 0 5px 0;
  color: #2c3e50;
  font-size: 1.1rem;
}

.course-info p {
  margin: 0 0 10px 0;
  color: #666;
  font-size: 0.9rem;
}

.progress-bar {
  display: flex;
  align-items: center;
  gap: 10px;
}

.progress-text {
  font-size: 0.9rem;
  color: #409EFF;
  font-weight: bold;
  min-width: 40px;
}

.exam-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.exam-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.exam-info h4 {
  margin: 0 0 5px 0;
  color: #2c3e50;
  font-size: 1rem;
}

.exam-info p {
  margin: 0;
  color: #666;
  font-size: 0.9rem;
}

.message-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.message-item {
  display: flex;
  gap: 15px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
}

.message-icon {
  font-size: 1.5rem;
  margin-top: 2px;
}

.message-content h4 {
  margin: 0 0 5px 0;
  color: #2c3e50;
  font-size: 1rem;
}

.message-content p {
  margin: 0 0 5px 0;
  color: #666;
  font-size: 0.9rem;
}

.message-time {
  font-size: 0.8rem;
  color: #999;
}

.quick-actions {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.quick-actions .el-button {
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .welcome-content {
    flex-direction: column;
    text-align: center;
  }
  
  .quick-stats {
    justify-content: center;
  }
  
  .content-grid {
    grid-template-columns: 1fr;
  }
  
  .quick-actions {
    grid-template-columns: 1fr;
  }
}
</style> 